import React, {useEffect, useRef, useState} from 'react';
import GoBack from "@/components/TheGoBack";
import {useLocation, useNavigate} from 'react-router-dom';
import {
    ProForm,
    ProFormCheckbox,
    ProFormColorPicker, ProFormDateTimePicker, ProFormDateTimeRangePicker, ProFormDependency,
    ProFormDigit,
    ProFormDigitRange,
    ProFormGroup, ProFormMoney,
    ProFormRadio,
    ProFormRate,
    ProFormSegmented,
    ProFormSelect,
    ProFormSlider,
    ProFormSwitch,
    ProFormText, ProFormTimePicker, ProFormTreeSelect,
    ProFormUploadButton,
    ProFormUploadDragger,
} from '@ant-design/pro-components';
import {Col, message, Row, Space, Form, Radio, Button} from "antd";
import {Divider, Typography} from 'antd';
import moment from "moment";
import {Decimal} from "decimal.js";
import '../../style/index.less';
import Goods from './goods.jsx';
import {
  apiGetGoodsClassifyTreeAll,
  apiQueryStoreClassifyTree,
  apiGetStoreInfo,
  apiGetBrandinfoList,
  apiAppCouponInfoAdd,
  apiAppCouponInfoEdit,
  apiGetCouponByIdListView
} from '@/api/couponManagement/couponsList.js'

const {Title, Paragraph, Text, Link} = Typography;

const Add = () => {
    const [isProprietary, setIsProprietary] = useState();
    const [dataSource, setDataSource] = useState({});
    const [selectClassifyKeys, setSelectClassifyKeys] = useState([]);
    const [selectBrandKeys, setSelectBrandKeys] = useState([]);
    const [expiryDateStartStatus, setExpiryDateStartStatus] = useState(true);
    const location = useLocation();
    const formRef = useRef();
    const GoodsRef = useRef();
    const format = "YYYY-MM-DD HH:mm";
    const mode = location.state.mode;
    const couponId = location.state.couponId;
    const navigate = useNavigate()

    let title = null
    switch (mode) {
        case 'add':
            title = "新建优惠券";
            break;
        case 'edit':
            title = "编辑优惠券";
            break;
        case 'view':
            title = "查看优惠券";
            break;
        default:
            break;
    }
    const [options, setOptions] = useState([
        {
            label: '线上商城',
            value: 'P',
        },
        {
            label: '门店服务',
            value: 'M',
        },
    ])
    useEffect(() => {

    }, [])
    const formItemLayout = {
        labelCol: {flex: "100px"},
        wrapperCol: {span: 'auto'},
    }
    const onValuesChange = (changedValues, allValues) => {
        // 券类型 与 优惠内容联动
        if ('couponType' in changedValues) {
            formRef.current.resetFields(["couponPrice"])
        }
        // 处理商品范围依赖业务类型字段值问题
        if ('couponSpecies' in changedValues) {
            if (changedValues.couponSpecies === 'M') {
                formRef.current.setFieldsValue({
                    couponType: 'J',
                    commodityScope: 0,
                    couponSourceCard: 1
                })
            }else {
              formRef.current.setFieldsValue({
                couponSourceCard: 0
            })
            }
            formRef.current.resetFields(["commodityScope"])
        }
        // 发放总量 选择交互判断
        if ('number' in changedValues) {
            if (changedValues.number === -1) {
                formRef.current.resetFields(["couponStockCount"])
            }
        }
        // 商品范围 优惠叠加交互
        if ('commodityScope' in changedValues) {
            formRef.current?.resetFields(["category", "goodsInfoList"])
            if (changedValues.commodityScope === 2) {
                formRef.current.setFieldsValue({activitySatisfy: 1})
            } else {
                formRef.current.setFieldsValue({activitySatisfy: 0})
            }
        }
        // 使用门槛 选择交互判断
        if ('usePrice' in changedValues) {
            if (changedValues.usePrice === -1) {
                formRef.current.resetFields(["usePriceNumber"])
            }
        }
        // 优惠内容 是否选择最大折扣金额
        if ('specialDiscountCheckbox' in changedValues) {
            if (changedValues.specialDiscountCheckbox === 'no') {
                formRef.current.resetFields(["couponMaxPrice"])
            }
        }
        // 活动时间 选择交互判断
        if ('activityTime' in changedValues) {
            if (changedValues.activityTime === 0) {
                formRef.current.resetFields(["activityTimeFixed"])
            }
        }
        // 当券有效期为指定时间 活动时间如更改 初始化有效期
        if ("activityTimeFixed" in changedValues) {
            formRef.current.resetFields(["expiryDateAppoint"])
        }
        // 券有效期 选择交互判断
        if ('timeType' in changedValues) {
            if (changedValues.timeType === 0) {
                formRef.current.resetFields([
                    "effectiveTimeTwo", "effectiveTimeOne", "takeEffectTime"
                ])
            } else if (changedValues.timeType === 1) {
                formRef.current.resetFields([
                    "expiryDateAppoint", "effectiveTimeTwo", "takeEffectTime"
                ])
            } else if (changedValues.timeType === 2) {
                formRef.current.resetFields([
                    "expiryDateAppoint", "effectiveTimeOne"
                ])
            }
        }
        // 商品 选择交互判断
        if ('category' in changedValues) {
            if (changedValues.category === 1) {
                formRef.current?.resetFields(["goodsBrand", "goodsInfoList"])
                GoodsRef.current?.resetData()
            } else if (changedValues.category === 3) {
                formRef.current?.resetFields(["goodsCategory", "goodsInfoList"])
                GoodsRef.current?.resetData()
            } else if (changedValues.category === 4) {
                formRef.current?.resetFields(["goodsCategory", "goodsBrand"])
            }
        }
        // 限领张数 选择交互判断
        if ('limitRadio' in changedValues) {
            if (changedValues.limitRadio === -1) {
                formRef.current.resetFields(["exchangeCountOne", "exchangeDays", "exchangeCountTwo"])
            } else if (changedValues.limitRadio === 2) {
                formRef.current.resetFields(["exchangeDays", "exchangeCountTwo"])
            } else if (changedValues.limitRadio === 3) {
                formRef.current.resetFields(["exchangeCountOne"])
            }
        }
        // 发放方式 选择交互判断
        if ('cdkeyState' in changedValues) {
            if (changedValues.cdkeyState === 1) {
                formRef.current.resetFields(["cdkeyNum"])
            }
        }
        if ('passwordState' in changedValues) {
            if (changedValues.passwordState === 1) {
                formRef.current.resetFields(["password", "passwordNum"])
            }
        }
        // 是否开启到期提醒
        if ('remindUser' in changedValues) {
            formRef.current.setFieldsValue({
                "remindNumber": !changedValues.remindUser ? null : 1
            })
        }
    }
    // 可领时间 禁止选择当天之前时间
    const range = (start, end) => {
        const result = [];
        for (let i = start; i <= end; i++) {
            result.push(i);
        }
        return result;
    };
    const disabledDate = (current, partial) => {
        // 禁止选择活动结束时间之后
        setTimeout(() => {
            let {activityTime, activityTimeFixed} = formRef.current?.getFieldsValue()
            if (activityTime && activityTimeFixed && expiryDateStartStatus) {
                return current.isAfter(activityTimeFixed[1])
            }
        }, 1000)
    };
    const disabledDateTime = (current, partial) => {
        // 当为开始时间时disabledDate做禁止(天)校验
        if (partial === 'start') {
            setExpiryDateStartStatus(true)
        } else {
            setExpiryDateStartStatus(false)
        }
        // 时分禁止校验
        let {activityTime, activityTimeFixed} = formRef.current?.getFieldsValue()
        if (activityTime && activityTimeFixed) {
            let hour = moment(activityTimeFixed[1]).hour()
            let minutes = moment(activityTimeFixed[1]).minutes()
            if (current && moment(current).date() === moment(activityTimeFixed[1]).date() && partial === 'start') {
                return {
                    disabledHours: () => range(hour, 23).slice(1),
                    disabledMinutes: () => range(minutes, 59)
                };
            }
        }
    };
    // 商品类目回显遍历禁用项
    const matterTree = (data) => {
        data.map((item, index) => {
            if (selectClassifyKeys.includes(item.value)) {
                item.disabled = true
            }
            if (item.children && item.children.length > 0) {
                matterTree(item.children)
            }
        })
        return data
    }
    // 去除不使用的undefined字段
    const dataFilter = (data) => {
        return Object.keys(data)
            .filter((key) => data[key] !== null && data[key] !== undefined)
            .reduce((acc, key) => ({...acc, [key]: data[key]}), {});
    }
    // value 被 transform转化之后的值
    const transform = (value) => {
        let params = dataFilter(value)
        // let { mode, couponId, dataSource } = this.state
        // 活动时间 固定时间
        if ('activityTimeFixed' in params) {
            // params.activityStartTime = params.activityTimeFixed[0]
            // params.activityStopTime = params.activityTimeFixed[1]
            delete params.activityTimeFixed
        }
        // 商品范围
        if ('commodityScope' in params) {
            if (params.commodityScope === 2) {
                params.category = 4
            }
        }
        // 券有效期 指定日期
        if ('timeType' in params) {
            if ('expiryDateAppoint' in params) {
                // params.startTime = params.expiryDateAppoint[0]
                // params.endTime = params.expiryDateAppoint[1]
                delete params.expiryDateAppoint
            }
            if (params.timeType === 1) {
                params.effectiveTime = params.effectiveTimeOne
                delete params.effectiveTimeOne
            }
            if (params.timeType === 2) {
                params.effectiveTime = params.effectiveTimeTwo
                delete params.effectiveTimeTwo
            }
        }
        // 发放总量
        if ('number' in params) {
            if (params.number === -1) {
                params.couponStock = -1
                params.couponStockCount = -1
            } else if (mode === 'edit') {
                params.couponStock = dataSource.couponStock
                if (dataSource.couponStockCount !== -1) {
                    params.subStock = params.couponStockCount - dataSource.couponStockCount
                }
            } else {
                params.couponStock = params.couponStockCount
            }
            delete params.number
        }
        // 使用门槛
        if ("usePrice" in params) {
            if (params.usePrice === 2) {
                params.usePrice = params.usePriceNumber
                delete params.usePriceNumber
            }
        }
        // 优惠金额 去除checkbox字段值
        if ("specialDiscountCheckbox" in params) {
            delete params.specialDiscountCheckbox
        }
        // 领取限制
        if ('limitRadio' in params) {
            if (params.limitRadio === -1) {
                params.exchangeDays = -1
                params.exchangeCount = -1
            }
            if (params.limitRadio === 2) {
                params.exchangeCount = params.exchangeCountOne
                delete params.exchangeCountOne
            }
            if (params.limitRadio === 3) {
                params.exchangeCount = params.exchangeCountTwo
                delete params.exchangeCountTwo
            }
            delete params.limitRadio
        }
        // 商品
        if ('category' in params) {
            if (params.category === 1) {
                params.dataType = {
                    category: params.category,
                    classifyTypeList: params.goodsCategory
                }
                delete params.goodsCategory
            }
            if (params.category === 3) {
                params.dataType = {
                    category: params.category,
                    brands: params.goodsBrand
                }
                delete params.goodsBrand
            }
            if (params.category === 4) {
                params.dataType = {
                    category: params.category,
                    goodsInfos: params.goodsInfoList
                }
                delete params.goodsInfoList
            }
            delete params.category
        }

        if (mode === 'edit') {
            // params.cdkeyNum = params.cdkeyNum - dataSource.cdkeyNum
            params.cdkeyOldNumber = dataSource.cdkeyNum
        }
        return params
    }

    const editform = (value) => {
        let params = dataFilter(value)
        // 活动时间 固定时间
        if (params.activityStartTime && params.activityStopTime) {
            params.activityTimeFixed = [params.activityStartTime, params.activityStopTime]
            delete params.activityStartTime
            delete params.activityStopTime
        }
        // 商品范围
        if ('commodityScope' in params) {
            if (params.commodityScope === 2) {
                params.category = 4
            }
        }
        // 券有效期 指定日期
        if (params.startTime && params.endTime) {
            params.expiryDateAppoint = [params.startTime, params.endTime]
            delete params.startTime
            delete params.endTime
            delete params.takeEffectTime
        } else if (params.takeEffectTime !== -1) {
            params.effectiveTimeTwo = params.effectiveTime
        } else {
            params.effectiveTimeOne = params.effectiveTime
            delete params.takeEffectTime
        }
        // 发放总量
        if ('couponStock' in params) {
            if (params.couponStock === -1) {
                params.number = -1
                delete params.couponStock
                delete params.couponStockCount
            } else {
                params.number = 2
            }
        }
        // 使用门槛
        if ("usePrice" in params) {
            if (params.usePrice !== -1) {
                params.usePriceNumber = params.usePrice
                params.usePrice = 2
            }
        }
        // 优惠金额
        if (params.couponMaxPrice !== -1) {
            params.specialDiscountCheckbox = 'yes'
        } else {
            delete params.couponMaxPrice
        }
        // 领取限制
        if (params.exchangeDays === -1 && params.exchangeCount === -1) {
            params.limitRadio = -1
            delete params.exchangeDays
        } else {
            if (params.exchangeDays !== -1) {
                params.limitRadio = 3
                params.exchangeCountTwo = params.exchangeCount
                delete params.exchangeCount
            } else {
                params.limitRadio = 2
                params.exchangeCountOne = params.exchangeCount
                delete params.exchangeCount
                delete params.exchangeDays
            }
        }
        // CDK关联
        if (params.cdkeyState) {
            delete params.cdkeyNum
        }
        // 口令
        if (params.passwordState) {
            delete params.passwordNum
        }
        if (params.dataType) {
            let {category, brands, classifyTypeList, goodsInfos} = params.dataType
            // 下级类别
            if (category) {
                params.category = category
            }
            // 类目
            if (classifyTypeList) {
                params.goodsCategory = classifyTypeList
                // this.setState({
                //   selectClassifyKeys: classifyTypeList
                // })
            }
            // 品牌
            if (brands) {
                params.goodsBrand = brands
                // this.setState({
                //   selectBrandKeys: brands
                // })
            }
            // 商品
            if (goodsInfos) {
                params.goodsInfoList = goodsInfos
                // this.setState({
                //   selectGoodsKeys: goodsInfos.map(item => {
                //     return item.goodsId
                //   }),
                //   goodsDefault: goodsInfos
                // })
            }
        }
        return params
    }

  return (
    <div className={'wrap-box'}>
      <GoBack title={title} />
      <div className={'wrap-box-content'}>
        <ProForm
          {...formItemLayout}
          disabled={mode === 'view'}
          formRef={formRef}
          layout={'horizontal'}
          submitter={{
            render: (props, doms) => {
              if (mode === 'view') {
                return null
              }
              return <Row>
                <Col span={22} offset={2}>
                  <Space>{doms}</Space>
                </Col>
              </Row>
            },
          }}
          onValuesChange={onValuesChange}
          onFinish={async (values) => {
            // await waitTime(2000);
            return await new Promise((resolve) => {
              let params = transform(values);
              // 添加
              if (mode === 'add') {
                apiAppCouponInfoAdd(params).then(res=>{
                  if (res.code === 0 && res.data) {
                    message.success('新建成功');
                    navigate(-1)
                  }
                  resolve(true)
                })
              } else {
                apiAppCouponInfoEdit({
                  ...params, couponId
                }).then(res=>{
                  if (res.code === 0 && res.data) {
                    message.success('修改成功');
                    navigate(-1)
                  }
                  resolve(true)
                })
              }
            })
          }}
          onFinishFailed={(values) => {
            if (values.errorFields.length) {
              message.error('请完善数据')
            }
          }}
          params={{}}
          initialValues={{
            couponSpecies: 'P',
            couponType: 'J',
            number: -1,
            usePrice: -1,
            commodityScope: 0,
            activityTime: 0,
            couponSourceDirect: 0,
            remindUser: 1,
            remindNumber: 1,
            activitySatisfy: 0,
            activityPresented: 1,
            // couponSourceCard: 1,
            goodsInfoList: []
          }}
          request={async () => {
            let storeInfo = await apiGetStoreInfo();
            let category = '';
            if (storeInfo.code === 0 && storeInfo.data) {
              // 经营类目：0实体门店、1酒店、2医院、3上门服务、4线上店铺
              if (storeInfo.data.businessCategory === "4") {
                category = 'P'
                setOptions([
                  {
                    label: '线上商城',
                    value: 'P',
                  }
                ])
              }
              else if (storeInfo.data.businessCategory !== "3") {
                category = 'M'
              }
              setIsProprietary(storeInfo.data.isProprietary)
            }
            if (mode !== "add") {
              let res = await apiGetCouponByIdListView(couponId)
              if (res.code === 0) {
                let data = editform(res.data)
                setDataSource(data)
                return {
                  couponSpecies: category,
                  ...data
                }
              }
            } else {
              return {
                couponSpecies: category
              };
            }
          }}
        >
          <Paragraph strong>
            <blockquote>基础设置</blockquote>
          </Paragraph>
          <ProFormRadio.Group
            name="couponSpecies"
            label="业务类型"
            // disabled
            options={options}
            rules={[{ required: true }]}
          />
          <ProFormText
            width="md"
            name="couponTitle"
            label="券名称"
            disabled={mode === 'edit' || mode === 'view'}
            fieldProps={{
              showCount: true,
              maxLength: 30
            }}
            rules={[{ required: true }]}
          />
          <ProFormDependency name={['couponSpecies']}>
            {({ couponSpecies }) => {
              return (
                <>
                  <ProFormSelect
                    width="md"
                    name="couponType"
                    label="券类型"
                    valueEnum={{
                      "J": '代金券',
                      "Z": '折扣券',
                    }}
                    fieldProps={{
                      disabled: mode === 'edit' || couponSpecies === 'M' || mode === 'view',
                    }}
                    rules={[{ required: true }]}
                  />
                  <ProFormSelect
                    width="md"
                    name="commodityScope"
                    label="商品范围"
                    options={[
                      {
                        label: '全部商品可用',
                        value: 0,
                      },
                      {
                        label: '限制品类可用',
                        value: 1,
                      },
                      {
                        label: '商品券',
                        value: 2,
                      },
                    ]}
                    fieldProps={{
                      disabled: mode === 'edit' || couponSpecies === 'M' || mode === 'view',
                    }}
                    rules={[{ required: true }]}
                  />
                </>
              );
            }}
          </ProFormDependency>
          <ProFormRadio.Group
            name="number"
            label="发放总量"
            rules={[{ required: true }]}
            options={[
              {
                label: '不限',
                value: -1,
              },
              {
                value: 2,
                label: <ProFormDependency name={['number']}>
                  {({ number }) => {
                    return (
                      <Space>
                        <span>共</span>
                        <ProFormDigit
                          width="xs"
                          name="couponStockCount"
                          noStyle={true}
                          min={1}
                          max={999999}
                          rules={[
                            {
                              required: number !== -1,
                              message: '请输入发放总量'
                            },
                            {
                              min: (mode === 'edit' && (dataSource.couponStockCount - dataSource.couponStock !== 0)) ? (dataSource.couponStockCount - dataSource.couponStock) : 1,
                              type: "number",
                              message: `已发放给消费者${dataSource.couponStockCount - dataSource.couponStock}张，不可低于该值!`
                            }
                          ]}
                          fieldProps={{
                            disabled: number === -1,
                          }}
                        />
                        <span>张</span>
                        {mode === 'edit' && dataSource.couponStock !== -1 && dataSource.couponStock ? <span
                          className="ant-form-text ext">(剩余库存{dataSource.couponStock}张)</span> : null}
                      </Space>
                    )
                  }}
                </ProFormDependency>
              },
            ]}
          />
          <ProFormRadio.Group
            name="usePrice"
            label="使用门槛"
            disabled={mode === 'edit' || mode === 'view'}
            rules={[{ required: true }]}
            options={[
              {
                label: '不限',
                value: -1,
              },
              {
                value: 2,
                label: <ProFormDependency name={['usePrice']}>
                  {({ usePrice }) => {
                    return (
                      <Space>
                        <span>满</span>
                        <ProFormMoney
                          width="xs"
                          name="usePriceNumber"
                          noStyle={true}
                          min={0.01}
                          max={99999}
                          rules={[
                            {
                              required: usePrice !== -1,
                              message: '请输入门槛金额'
                            },
                          ]}
                          fieldProps={{
                            disabled: usePrice === -1 || mode === 'edit' || mode === 'view',
                          }}
                          formItemProps={{
                            getValueFromEvent: (args) => args ? Decimal(args).mul(Decimal(100)).toNumber() : 0,
                            getValueProps: v => ({
                              value: v ? Decimal(v).div(Decimal(100)).toNumber() : v,
                              v
                            }),
                          }}
                        />
                        <span>可用</span>
                      </Space>
                    )
                  }}
                </ProFormDependency>
              },
            ]}
          />
          <ProForm.Item
            label={<><span className={'required-rule'}>*</span>优惠内容</>}
          >
            <ProFormDependency name={['couponType']}>
              {({ couponType }) => {
                if (couponType === 'J') {
                  return (
                    <Space>
                      <span>减免</span>
                      <ProFormMoney
                        width={150}
                        name="couponPrice"
                        noStyle={true}
                        min={1}
                        max={2000}
                        disabled={mode === 'edit' || mode === 'view'}
                        rules={[
                          {
                            required: true,
                            message: '请输入优惠内容'
                          },
                        ]}
                        fieldProps={{
                          precision: 0,
                          placeholder: '请输入1~2000整数'
                          // disabled: usePrice === -1 || mode === 'view',
                        }}
                        formItemProps={{
                          getValueFromEvent: (args) => args ? Decimal(args).mul(Decimal(100)).toNumber() : 0,
                          getValueProps: v => ({
                            value: v ? Decimal(v).div(Decimal(100)).toNumber() : v,
                            v
                          }),
                        }}
                      />
                      <span>元</span>
                    </Space>
                  )
                } else if (couponType === 'Z') {
                  return <Space direction="vertical">
                    <Space>
                      <span>打</span>
                      <ProFormDigit
                        disabled={mode === 'edit' || mode === 'view'}
                        width="xs"
                        name="couponPrice"
                        noStyle={true}
                        min={0.1}
                        max={9.9}
                        rules={[
                          {
                            required: true,
                            message: '请输入折扣'
                          }
                        ]}
                        fieldProps={{
                          precision: 1,
                        }}
                        formItemProps={{
                          getValueFromEvent: (args) => args ? Decimal(args).mul(Decimal(10)).toNumber() : 0,
                          getValueProps: v => ({
                            value: v ? Decimal(v).div(Decimal(10)).toNumber() : v,
                            v
                          }),
                        }}
                      />
                      <span>折</span>
                    </Space>
                    <Space>
                      <ProFormCheckbox
                        disabled={mode === 'edit' || mode === 'view'}
                        name="specialDiscountCheckbox"
                        noStyle={true}
                        formItemProps={{
                          getValueFromEvent: (e) => (e.target.checked ? 'yes' : 'no'),
                          getValueProps: value => ({ checked: value === 'yes', value }),
                        }}
                      >
                        最大折扣金额:
                      </ProFormCheckbox>
                      <ProFormDependency name={['specialDiscountCheckbox']}>
                        {({ specialDiscountCheckbox }) => {
                          return <ProFormMoney
                            width={100}
                            name="couponMaxPrice"
                            noStyle={true}
                            min={1}
                            max={999}
                            rules={[
                              {
                                required: specialDiscountCheckbox === 'yes',
                                message: '请输入折扣金额'
                              },
                            ]}
                            fieldProps={{
                              precision: 0,
                              disabled: specialDiscountCheckbox !== 'yes' || mode === 'edit' || mode === 'view',
                            }}
                            formItemProps={{
                              getValueFromEvent: (args) => args ? Decimal(args).mul(Decimal(100)).toNumber() : 0,
                              getValueProps: v => ({
                                value: v ? Decimal(v).div(Decimal(100)).toNumber() : v,
                                v
                              }),
                            }}
                          />
                        }}
                      </ProFormDependency>
                      <span>元</span>
                    </Space>
                  </Space>
                }
              }}
            </ProFormDependency>
          </ProForm.Item>
          <ProFormRadio.Group
            name="activityTime"
            label="活动时间"
            disabled={mode === 'edit' || mode === 'view'}
            rules={[{ required: true }]}
            options={[
              {
                label: '长期',
                value: 0,
              },
              {
                value: 1,
                label: <ProFormDependency name={['activityTime']}>
                  {({ activityTime }) => {
                    return (
                      <Space>
                        <span>固定时间</span>
                        <ProFormDateTimeRangePicker
                          noStyle
                          width="md"
                          name={'activityTimeFixed'}
                          showTime
                          fieldProps={{
                            // format: (value) => value.format(format),
                            format: 'YYYY-MM-DD HH:mm',
                            disabled: activityTime === 0 || mode === 'edit' || mode === 'view'
                          }}
                          transform={(values) => {
                            return {
                              activityStartTime: values ? values[0] : undefined,
                              activityStopTime: values ? values[1] : undefined,
                            };
                          }}
                          rules={[
                            {
                              required: activityTime !== 0,
                              message: '请选择固定时间'
                            }
                          ]}
                        />
                      </Space>
                    )
                  }}
                </ProFormDependency>
              },
            ]}
          />
          <ProFormRadio.Group
            name="timeType"
            label="券有效期"
            disabled={mode === 'edit' || mode === 'view'}
            layout="vertical"
            rules={[{ required: true, message: "请选择券有效期" }]}
            options={[
              {
                value: 0,
                label: <ProFormDependency name={['timeType']}>
                  {({ timeType }) => {
                    return (
                      <Space>
                        <span>指定日期</span>
                        <ProFormDateTimeRangePicker
                          noStyle
                          width="md"
                          name={'expiryDateAppoint'}
                          // dependencies={['activityTimeFixed']}
                          showTime
                          fieldProps={{
                            // format: (value) => value.format(format),
                            format: 'YYYY-MM-DD HH:mm',
                            disabled: timeType !== 0 || mode === 'edit' || mode === 'view',
                            disabledDate: disabledDate,
                            disabledTime: disabledDateTime
                          }}
                          transform={(values) => {
                            return {
                              startTime: values ? values[0] : undefined,
                              endTime: values ? values[1] : undefined,
                            };
                          }}
                          rules={[
                            {
                              required: timeType === 0 && timeType !== undefined,
                              message: '请选择指定日期'
                            }
                          ]}
                        />
                      </Space>
                    )
                  }}
                </ProFormDependency>
              },
              {
                value: 1,
                label: <ProFormDependency name={['timeType']}>
                  {({ timeType }) => {
                    return (
                      <Space>
                        <span>领券后</span>
                        <ProFormDigit
                          width="xs"
                          name={"effectiveTimeOne"}
                          noStyle={true}
                          min={1}
                          max={7300}
                          rules={[
                            {
                              required: timeType === 1,
                              message: '请输入天数'
                            }
                          ]}
                          fieldProps={{
                            precision: 0,
                            disabled: timeType !== 1 || mode === 'edit' || mode === 'view',
                          }}
                        />
                        <span>天内可用</span>
                      </Space>
                    )
                  }}
                </ProFormDependency>
              },
              {
                value: 2,
                label: <ProFormDependency name={['timeType']}>
                  {({ timeType }) => {
                    return (
                      <Space>
                        <span>领券后</span>
                        <ProFormDigit
                          width="xs"
                          name={'takeEffectTime'}
                          noStyle
                          min={1}
                          max={7300}
                          rules={[
                            {
                              required: timeType === 2,
                              message: '请输入天数'
                            }
                          ]}
                          fieldProps={{
                            precision: 0,
                            disabled: timeType !== 2 || mode === 'edit' || mode === 'view',
                          }}
                        />
                        <span>天后生效，</span>
                        <ProFormDigit
                          width="xs"
                          name={"effectiveTimeTwo"}
                          noStyle={true}
                          min={1}
                          max={7300}
                          rules={[
                            {
                              required: timeType === 2,
                              message: '请输入天数'
                            }
                          ]}
                          fieldProps={{
                            precision: 0,
                            disabled: timeType !== 2 || mode === 'edit' || mode === 'view',
                          }}
                        />
                        <span>天内可用</span>
                      </Space>
                    )
                  }}
                </ProFormDependency>
              }
            ]}
          />
          <ProFormDependency name={['commodityScope']}>
            {({ commodityScope }) => {
              if (commodityScope === 1) {
                let option = [
                  {
                    value: 1,
                    label: <ProFormDependency name={['category']}>
                      {({ category }) => {
                        return (
                          <Space>
                            <span>类目</span>
                            <ProFormTreeSelect
                              name="goodsCategory"
                              placeholder="请选择商品类目"
                              allowClear
                              noStyle
                              width={'md'}
                              rules={[
                                {
                                  required: category === 1,
                                  message: '请选择商品类目'
                                }
                              ]}
                              fieldProps={{
                                disabled: category !== 1 || mode === 'view',
                                treeCheckable: true,
                                onClick: (e) => e.preventDefault()
                              }}
                              request={async () => {
                                let res = await apiQueryStoreClassifyTree()
                                if (res.code === 0) {
                                  return matterTree(res.data)
                                } else {
                                  return []
                                }
                              }}
                            />
                          </Space>
                        )
                      }}
                    </ProFormDependency>
                  },
                  // {
                  //   value: 3,
                  //   label: <ProFormDependency name={['category']}>
                  //     {({ category }) => {
                  //       return (
                  //         <Space>
                  //           <span>品牌</span>
                  //           <ProFormSelect
                  //             width={'md'}
                  //             name="goodsBrand"
                  //             noStyle
                  //             request={async () => {
                  //               const res = await apiGetBrandinfoList()
                  //               if (res.code === 0) {
                  //                 return res.data.map((v) => {
                  //                   return {
                  //                     value: v.brandId,
                  //                     label: v.brandName,
                  //                     disabled: selectBrandKeys.includes(v.brandId)
                  //                   }
                  //                 })
                  //               } else {
                  //                 return []
                  //               }
                  //             }}
                  //             fieldProps={{
                  //               disabled: category !== 3 || mode === 'view',
                  //               showSearch: true,
                  //               onClick: (e) => e.preventDefault()
                  //             }}
                  //             mode="multiple"
                  //             placeholder="请选择商品品牌"
                  //             rules={[{
                  //               required: category === 3,
                  //               message: '请选择商品品牌'
                  //             }]}
                  //           />
                  //         </Space>
                  //       )
                  //     }}
                  //   </ProFormDependency>
                  // },
                  {
                    value: 4,
                    label: <ProFormDependency name={['category']}>
                      {({ category }) => {
                        return (
                          <Space>
                            <span>部分商品</span>
                            <Button disabled={category !== 4}
                              onClick={() => GoodsRef.current.open()}>选择商品</Button>

                                                    </Space>
                                                )
                                            }}
                                        </ProFormDependency>
                                    }
                                ];
                                if (isProprietary === 'N') {
                                    option.splice(1, 1)
                                }
                                return (
                                    <>
                                        <ProFormRadio.Group
                                            name="category"
                                            label="商品"
                                            disabled={mode === 'edit' || mode === 'view'}
                                            layout="vertical"
                                            rules={[{required: true, message: "请选择对应分类及内容"}]}
                                            options={option}
                                        />
                                        <ProFormDependency name={['category']}>
                                            {({category}) => {
                                                return <ProForm.Item
                                                    style={{
                                                        marginLeft: 100,
                                                        // marginTop: -20
                                                    }}
                                                    name="goodsInfoList"
                                                    trigger="onValuesChange"
                                                    rules={[{
                                                        required: category === 4,
                                                        message: '请选择商品'
                                                    }]}
                                                >
                                                    <Goods mode={mode} ref={GoodsRef}/>
                                                </ProForm.Item>
                                            }}
                                        </ProFormDependency>
                                    </>
                                )
                            }
                            if (commodityScope === 2) {
                                return <ProForm.Item
                                    label={'商品'}
                                    name="goodsInfoList"
                                    trigger="onValuesChange"
                                    rules={[{
                                        required: true,
                                        message: '请选择商品'
                                    }]}
                                >
                                    <Goods mode={mode} ref={GoodsRef} type={'single'}/>
                                </ProForm.Item>
                            }
                        }}
                    </ProFormDependency>
                    <Paragraph strong>
                        <blockquote>其他设置</blockquote>
                    </Paragraph>
                    <ProFormRadio.Group
                        name="limitRadio"
                        label="限领张数"
                        layout="vertical"
                        rules={[{required: true, message: "请选择限领方式"}]}
                        options={[
                            {
                                value: -1,
                                label: <ProFormText noStyle>不限</ProFormText>
                            },
                            {
                                value: 2,
                                label: <ProFormDependency name={['limitRadio']}>
                                    {({limitRadio}) => {
                                        return (
                                            <Space>
                                                <span>每人限领</span>
                                                <ProFormDigit
                                                    width="xs"
                                                    name={"exchangeCountOne"}
                                                    noStyle
                                                    min={1}
                                                    max={9}
                                                    rules={[
                                                        {
                                                            required: limitRadio === 2,
                                                            message: '请输入张数'
                                                        }
                                                    ]}
                                                    fieldProps={{
                                                        precision: 0,
                                                        disabled: limitRadio !== 2,
                                                    }}
                                                />
                                                <span>张</span>
                                            </Space>
                                        )
                                    }}
                                </ProFormDependency>
                            },
                            {
                                value: 3,
                                label: <ProFormDependency name={['limitRadio']}>
                                    {({limitRadio}) => {
                                        return (
                                            <Space>
                                                <span>每人每</span>
                                                <ProFormDigit
                                                    width="xs"
                                                    name={'exchangeDays'}
                                                    noStyle
                                                    min={1}
                                                    max={7300}
                                                    rules={[
                                                        {
                                                            required: limitRadio === 3,
                                                            message: '请输入天数'
                                                        }
                                                    ]}
                                                    fieldProps={{
                                                        precision: 0,
                                                        disabled: limitRadio !== 3,
                                                    }}
                                                />
                                                <span>日，限领</span>
                                                <ProFormDigit
                                                    width="xs"
                                                    name={"exchangeCountTwo"}
                                                    noStyle={true}
                                                    min={1}
                                                    max={9}
                                                    rules={[
                                                        {
                                                            required: limitRadio === 3,
                                                            message: '请输入天数'
                                                        }
                                                    ]}
                                                    fieldProps={{
                                                        precision: 0,
                                                        disabled: limitRadio !== 3,
                                                    }}
                                                />
                                                <span>张</span>
                                            </Space>
                                        )
                                    }}
                                </ProFormDependency>
                            },
                        ]}
                    />
                    <ProFormDependency name={['couponSpecies']}>
                        {({couponSpecies}) => {
                            return <ProForm.Item
                                label="发放方式"
                                className={'cdk-check-group'}
                            >
                                {(couponSpecies === "M") ?
                                    <ProFormCheckbox
                                        name="couponSourceCard"
                                        noStyle
                                        disabled
                                        initialValue={1}
                                        formItemProps={{
                                            getValueProps: value => ({checked: value === 1, value}),
                                            getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                        }}
                                    >
                                        绑定会员卡类型，购买该卡后发放
                                    </ProFormCheckbox>
                                    :
                                    <Space direction={'vertical'}>
                                        <ProFormCheckbox
                                            name="couponSourceDirect"
                                            noStyle
                                            formItemProps={{
                                                getValueProps: value => ({checked: value === 1, value}),
                                                getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                            }}
                                        >
                                            <Space>
                                                <span>可直接领取</span>
                                                <ProFormDependency name={['couponSourceDirect']}>
                                                    {({couponSourceDirect}) => {
                                                        if (couponSourceDirect) {
                                                            return <Space>
                                                                <span>可领时间</span>
                                                                <ProFormDateTimePicker
                                                                    name="receiveTime"
                                                                    noStyle
                                                                    fieldProps={{
                                                                        format: (value) => value.format(format),
                                                                        showTime: {
                                                                            format: 'HH:mm',
                                                                        },
                                                                    }}
                                                                    rules={[{
                                                                        required: true,
                                                                        message: '请选择可领时间'
                                                                    }]}
                                                                />
                                                            </Space>
                                                        }
                                                    }}
                                                </ProFormDependency>
                                            </Space>
                                        </ProFormCheckbox>
                                        <ProFormCheckbox
                                            name="cdkeyState"
                                            formItemProps={{
                                                getValueProps: value => ({checked: value === 0, value}),
                                                getValueFromEvent: (e) => (e.target.checked ? 0 : 1),
                                            }}
                                            noStyle
                                            disabled={mode === 'edit' && dataSource.cdkeyState === 0 || mode === 'view'}
                                        >
                                            <Space>
                                                <span>CDK关联</span>
                                                <span>发放数量</span>
                                                <ProFormDependency
                                                    name={['cdkeyState', 'couponStockCount', 'cdkeyNum']}>
                                                    {({cdkeyState, couponStockCount, cdkeyNum}) => {
                                                        let value = cdkeyState !== 0 || mode === 'view'
                                                        let total = couponStockCount ?? Infinity;
                                                        let cdk = cdkeyNum ?? 0;
                                                        return <ProFormDigit
                                                            width="xs"
                                                            name={"cdkeyNum"}
                                                            dependencies={['couponStockCount']}
                                                            noStyle
                                                            rules={[
                                                                {
                                                                    required: !value,
                                                                    message: '请输入数量'
                                                                },
                                                                {
                                                                    max: total,
                                                                    type: "number",
                                                                    message: `数量高于优惠券总库存数量${cdk - total}张!`
                                                                },
                                                                {
                                                                    min: (mode === 'edit' && dataSource.cdkeyNum !== -1) ? dataSource.cdkeyNum : 0,
                                                                    type: "number",
                                                                    message: `CDK数量只能新增!`
                                                                },
                                                            ]}
                                                            fieldProps={{
                                                                precision: 0,
                                                                disabled: value,
                                                            }}
                                                        />
                                                    }}
                                                </ProFormDependency>

                                            </Space>
                                        </ProFormCheckbox>
                                        <ProFormCheckbox
                                            name="passwordState"
                                            formItemProps={{
                                                getValueProps: value => ({checked: value === 0, value}),
                                                getValueFromEvent: (e) => (e.target.checked ? 0 : 1),
                                            }}
                                            noStyle
                                            disabled={mode === 'edit' && dataSource.passwordState === 0 || mode === 'view'}
                                        >
                                            <ProFormDependency
                                                name={['passwordState', 'couponStockCount', 'passwordNum']}>
                                                {({passwordState, couponStockCount, passwordNum}) => {
                                                    let value = passwordState !== 0 || mode === 'view'
                                                    let total = couponStockCount ?? Infinity;
                                                    let command = passwordNum ?? 0;
                                                    return <Space>
                                                        <span>口令关联</span>
                                                        <span>口令</span>
                                                        <ProFormText
                                                            width="xs"
                                                            name={"password"}
                                                            noStyle
                                                            rules={[
                                                                {
                                                                    required: !value,
                                                                    message: '请输入口令'
                                                                }
                                                            ]}
                                                            fieldProps={{
                                                                disabled: value,
                                                            }}
                                                        />
                                                        <span>发放数量</span>
                                                        <ProFormDigit
                                                            width="xs"
                                                            name={"passwordNum"}
                                                            dependencies={['couponStockCount']}
                                                            noStyle
                                                            rules={[
                                                                {
                                                                    required: !value,
                                                                    message: '请输入数量'
                                                                },
                                                                {
                                                                    max: total,
                                                                    type: "number",
                                                                    message: `数量高于优惠券总库存数量${command - total}张!`
                                                                },
                                                                {
                                                                    min: (mode === 'edit' && dataSource.passwordNum !== -1) ? dataSource.cdkeyNum : 0,
                                                                    type: "number",
                                                                    message: `不能低于口令已兑换的张数!`
                                                                },
                                                            ]}
                                                            min={1}
                                                            fieldProps={{
                                                                precision: 0,
                                                                disabled: value,
                                                            }}
                                                        />
                                                    </Space>
                                                }}
                                            </ProFormDependency>
                                        </ProFormCheckbox>
                                        {
                                            isProprietary === 'Y' ? <>
                                                <ProFormCheckbox
                                                    name="couponSourceRegister"
                                                    noStyle
                                                    formItemProps={{
                                                        getValueProps: value => ({checked: value === 1, value}),
                                                        getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                                    }}
                                                >
                                                    注册赠送
                                                </ProFormCheckbox>
                                                <ProFormCheckbox
                                                    name="couponSourceShare"
                                                    noStyle
                                                    formItemProps={{
                                                        getValueProps: value => ({checked: value === 1, value}),
                                                        getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                                    }}
                                                >
                                                    分享成功赠送
                                                </ProFormCheckbox>
                                                <ProFormCheckbox
                                                    name="couponSourceCard"
                                                    noStyle
                                                    formItemProps={{
                                                        getValueProps: value => ({checked: value === 1, value}),
                                                        getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                                    }}
                                                >
                                                    绑定会员卡类型，购买该卡后发放
                                                </ProFormCheckbox>
                                            </> : null
                                        }
                                    </Space>
                                }
                            </ProForm.Item>
                        }}
                    </ProFormDependency>
                    <ProFormDependency name={['couponSpecies']}>
                        {({couponSpecies}) => {
                            return couponSpecies === "P" ? <>
                                <ProFormCheckbox
                                    disabled={mode === 'edit'}
                                    name="couponUsablePlatform"
                                    label="适用平台"
                                    formItemProps={{
                                        getValueProps: value => ({checked: value === 'APP', value}),
                                        getValueFromEvent: (e) => (e.target.checked ? 'APP' : undefined),
                                    }}
                                >
                                    仅限APP
                                </ProFormCheckbox>
                                <ProFormCheckbox
                                    name="remindUser"
                                    label="到期提醒"
                                    formItemProps={{
                                        getValueProps: value => ({checked: value === 1, value}),
                                        getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                    }}
                                >
                                    <Space>
                                        <span>提前</span>
                                        <ProFormDependency name={['remindUser']}>
                                            {({remindUser}) => {
                                                return <ProFormSelect
                                                    name="remindNumber"
                                                    noStyle
                                                    rules={[{
                                                        required: remindUser === 1,
                                                        message: '请选择天数'
                                                    }]}
                                                    disabled={remindUser !== 1 || mode === 'view'}
                                                    options={[
                                                        {label: '1', value: '1'},
                                                        {label: '2', value: '2'},
                                                        {label: '3', value: '3'},
                                                        {label: '4', value: '4'},
                                                        {label: '5', value: '5'},
                                                    ]}
                                                    fieldProps={{
                                                        onClick: (e) => e.preventDefault()
                                                    }}
                                                />
                                            }}
                                        </ProFormDependency>
                                        <span>天提醒用户</span>
                                    </Space>
                                </ProFormCheckbox>
                                <ProForm.Item
                                    label="优惠叠加"
                                >
                                    <ProFormDependency name={['commodityScope']}>
                                        {({commodityScope}) => {
                                            return <Space>
                                                <ProFormCheckbox
                                                    name="activityNewPerson"
                                                    noStyle
                                                    disabled
                                                    formItemProps={{
                                                        getValueProps: value => ({checked: value === 1, value}),
                                                        getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                                    }}
                                                >
                                                    新人活动
                                                </ProFormCheckbox>
                                                <ProFormCheckbox
                                                    name="activitySeckill"
                                                    noStyle
                                                    disabled
                                                    formItemProps={{
                                                        getValueProps: value => ({checked: value === 1, value}),
                                                        getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                                    }}
                                                >
                                                    秒杀
                                                </ProFormCheckbox>
                                                <ProFormCheckbox
                                                    name="activitySpecial"
                                                    noStyle
                                                    formItemProps={{
                                                        getValueProps: value => ({checked: value === 1, value}),
                                                        getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                                    }}
                                                >
                                                    特惠
                                                </ProFormCheckbox>
                                                <ProFormCheckbox
                                                    name="activitySatisfy"
                                                    noStyle
                                                    disabled={commodityScope === 0 || commodityScope === 1 || mode === 'view'}
                                                    formItemProps={{
                                                        getValueProps: value => ({checked: value === 1, value}),
                                                        getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                                    }}
                                                >
                                                    满减
                                                </ProFormCheckbox>
                                                <ProFormCheckbox
                                                    name="activityPresented"
                                                    noStyle
                                                    disabled
                                                    formItemProps={{
                                                        getValueProps: value => ({checked: value === 1, value}),
                                                        getValueFromEvent: (e) => (e.target.checked ? 1 : 0),
                                                    }}
                                                >
                                                    满赠
                                                </ProFormCheckbox>
                                            </Space>
                                        }}
                                    </ProFormDependency>
                                </ProForm.Item>
                            </> : null
                        }}
                    </ProFormDependency>
                </ProForm>
            </div>
        </div>
    )
};
export default Add;
